import React, { Key, useState } from 'react';
import { Button, Tree, TreeDataNode, TreeProps, Modal } from 'antd';
import { PlusCircleOutlined, CheckOutlined } from '@ant-design/icons';
import { Utils } from 'lfun-bg-comp';
import _ from 'lodash';
import style from './index.less';
import TreeItem from './treeItem';
import { Org, searchOrg } from '@/service/unit/org';
import { PageResult, Result } from '@/service';
import Create from './create';
import Delete from './delete';
import Update from './update';
import PermissionButton from '@/component/permission-button';

const Groups: React.FC<{ parentId: any; onSelect: (selectedKeys: React.Key[]) => void }> = ({ parentId, onSelect }) => {
  const [showLine] = useState<boolean>(true);
  const [showIcon] = useState<boolean>(false);
  const [showLeafIcon] = useState<React.ReactNode>(true);
  const [treeData, setTreeData] = useState<TreeDataNode[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<Key[]>([]);
  const [isAddModal, setIsAddModal] = useState<boolean>(false);
  const [isEditModal, setIsEditModal] = useState<boolean>(false);
  const [isDelModal, setIsDelModal] = React.useState<boolean>(false);
  const [selectedKey, setSelectedKey] = useState<Key>('');
  const [currentData, setCurrentData] = useState<any>({});
  const [count, setCount] = useState<number>(0);
  const isSchool = Utils.getProps('isSchool');

  const init = async () => {
    const result: Result<PageResult<Org>> = await searchOrg({});
    if (result.success) {
      let _count = 0;
      const curChildren: Org[] = result?.data?.items?.filter(it => String(it.parent_id) === parentId);
      if (curChildren && curChildren.length > 0) {
        const _expandedKeys = [];
        const children: TreeDataNode[] = curChildren.map((it: Org) => {
          _expandedKeys.push(it.id);
          _count += it.member_cnt;
          const subChildren = result?.data?.items?.filter(subit => subit.parent_id === it.id);
          return {
            title: <TreeItem text={`${it.org_name}(${it.member_cnt})`} hasAdd="true" {...buildTreeDataProps(it)} />,
            key: it.id,
            children: subChildren.map((subit: Org) => {
              return {
                title: <TreeItem text={`${subit.org_name}(${subit.member_cnt})`} {...buildTreeDataProps(subit)} />,
                key: subit.id,
              };
            }),
          };
        });
        setTreeData(children);
        setExpandedKeys([..._expandedKeys]);
        setCount(_count);
        if (_expandedKeys && _expandedKeys.length > 0)
          onChangeSelect(
            [
              _expandedKeys[0],
              ...result?.data?.items?.filter(it => it.parent_id === _expandedKeys[0]).map(it => it.id),
            ],
            null
          );
      } else {
        setTreeData([]);
        setExpandedKeys([]);
        onChangeSelect([], null);
        onSelect([]);
      }
    }
  };

  React.useEffect(() => {
    if (parentId > 0) init();
  }, [parentId]);

  const buildTreeDataProps = (data: any): any => {
    if (isSchool) return {};
    return {
      onAdd: () => {
        setCurrentData(data);
        setIsAddModal(true);
      },
      onEdit: () => {
        setCurrentData(data);
        setIsEditModal(true);
      },
      onDel: () => {
        setCurrentData(data);
        setIsDelModal(true);
      },
    };
  };

  const onChangeSelect = (selectedKeys: React.Key[], info: any) => {
    if (selectedKeys && selectedKeys.length > 0) {
      setSelectedKey(selectedKeys[0]);
      const children: TreeDataNode[] = treeData.find(it => it.key === selectedKeys[0])?.children || [];
      onSelect([...selectedKeys, ...children.map(it => it.key)]);
    }
  };

  const onExpand: TreeProps['onExpand'] = expandedKeysValue => {
    console.log('onExpand', expandedKeysValue);
    setExpandedKeys(expandedKeysValue);
  };

  return (
    <>
      {isSchool && (
        <PermissionButton permission="add">
          <Button
            className={style.tool_ant_btn}
            onClick={() => {
              setCurrentData({ id: parentId });
              setIsAddModal(true);
            }}
          >
            <PlusCircleOutlined />
            新建部门
          </Button>
        </PermissionButton>
      )}

      <Button className={style.tool_ant_btn_all}>全部人员({count}人)</Button>
      <Tree
        showLine={showLine ? { showLeafIcon } : false}
        showIcon={showIcon}
        expandedKeys={expandedKeys}
        onSelect={onChangeSelect}
        treeData={treeData}
        onExpand={onExpand}
        selectedKeys={[selectedKey]}
        blockNode
      />
      <PermissionButton permission="add">
        <Create
          show={isAddModal}
          onCancel={() => setIsAddModal(false)}
          onOk={(org: Org) => {
            init();
            setIsAddModal(false);
          }}
          currentData={currentData}
        />
      </PermissionButton>
      <PermissionButton permission="delete">
        <Delete
          show={isDelModal}
          onCancel={() => setIsDelModal(false)}
          onOk={() => {
            _.remove(treeData, item => {
              if (item.children) {
                _.remove(item.children, item => {
                  return item.key === currentData.id;
                });
              }
              return item.key === currentData.id;
            });
            setTreeData([...treeData]);
            setIsDelModal(false);
          }}
          currentData={currentData}
        />
      </PermissionButton>
      <PermissionButton permission="edit">
        <Update
          show={isEditModal}
          onCancel={() => setIsEditModal(false)}
          onOk={(org: Org) => {
            init();
            setIsEditModal(false);
          }}
          currentData={currentData}
        />
      </PermissionButton>
    </>
  );
};
export default Groups;
